package channel

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/query"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/withdraw"
	model0 "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/user/channel"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type PixWalletModel struct {
	ctx context.Context
	db  *gorm.DB
	logx.Logger
}

func (m *PixWalletModel) getDB() *gorm.DB {
	return m.db
}

func NewPixWalletModel(ctx context.Context, db *gorm.DB) *PixWalletModel {
	return &PixWalletModel{
		ctx:    ctx,
		db:     db,
		Logger: logx.WithContext(ctx),
	}
}

func (m *PixWalletModel) UserPixWalletsDel(in *rpc.UserPixWalletsDelRequest) (*rpc.UserPixWalletsDelsResponse, error) {
	del := m.db.Where("id = ?", in.Id)
	tx := del.Delete(&channel.UserChannelPix{
		Model: model0.Model{
			ID: (in.Id),
		},
	})
	if tx.Error != nil || tx.RowsAffected == 0 {
		return nil, xerrors.ErrDel
	}

	return &rpc.UserPixWalletsDelsResponse{
		IsDel: true,
	}, nil
}

// ------------------user channel pix ------------------
func (m *PixWalletModel) UserPixWalletsInfo(in *rpc.UserPixWalletsInfoRequest) (*rpc.UserPixWalletsInfoResponse, error) {
	var userPixWalletInfos []*channel.UserChannelPix
	var userPixWalletsList []*rpc.UserPixWalletsInfo

	// 查询所有用户银行信息
	query := m.db
	if in.UserId != 0 {
		query = query.Where("user_id = ?", in.UserId)
	}
	if in.WalletType != 0 {
		query = query.Where("wallet_type = ?", in.WalletType)
	}
	if in.Username != "" {
		query = query.Where("username LIKE ?", "%"+in.Username+"%")
	}
	if in.Cpf != "" {
		query = query.Where("cpf = ?", in.Cpf)
	}
	if in.Account != "" {
		query = query.Where("account LIKE ?", "%"+in.Account+"%")
	}
	query.Find(&userPixWalletInfos)

	for _, userPixWallet := range userPixWalletInfos {
		userBankInfo := &rpc.UserPixWalletsInfo{
			UserId:     userPixWallet.UserId,
			Account:    userPixWallet.Account,
			Username:   userPixWallet.UserName,
			WalletType: userPixWallet.WalletType,
			Cpf:        userPixWallet.Cpf,
			Id:         userPixWallet.ID,
		}
		userPixWalletsList = append(userPixWalletsList, userBankInfo)
	}

	return &rpc.UserPixWalletsInfoResponse{
		UserPixWalletsInfoList: userPixWalletsList,
	}, nil
}

func (m *PixWalletModel) UserPixWalletsInsert(in *rpc.UserPixWalletsInsertRequest) (ret *rpc.UserPixWalletsInsertResponse, err error) {
	tx := m.db.Create(&channel.UserChannelPix{
		UserId:     in.UserId,
		Account:    in.Account,
		Cpf:        in.Cpf,
		WalletType: in.WalletType,
		UserName:   in.Username,
	})
	if tx.Error != nil || tx.RowsAffected == 0 {
		return nil, xerrors.ErrInsert
	}
	g := query.Use(tx).UserChannelPix

	if in.WalletType == 3 {
		d, _ := g.Where(g.UserId.Eq(in.UserId)).Where(g.Account.Eq(in.Account)).Where(g.Cpf.Eq(in.Cpf)).Where(g.Cpf.Eq(in.Cpf)).First()
		m := withdraw.NewUserAuthModel(m.ctx, m.db)
		_, err = m.UserAuthModelAdd(&rpc.UserAuth{
			ID:       d.ID,
			UserId:   in.GetUserId(),
			UserName: in.GetUsername(),
			UserAuth: in.GetCpf(),
		})
	}

	if err != nil {
		return nil, err
	}
	return &rpc.UserPixWalletsInsertResponse{
		IsInsert: true,
	}, nil
}

func (m *PixWalletModel) UserPixWalletsPage(in *rpc.UserPixWalletsPageRequest) (*rpc.UserPixWalletsPageResponse, error) {
	var userChannelPixInfos []*channel.UserChannelPix
	offset := in.Page.PageSize * (in.Page.PageNo - 1)

	// 查询所有用户银行信息
	query := m.db.Model(&channel.UserChannelPix{})
	if in.Param.UserId != 0 {
		query = query.Where("user_id = ?", in.Param.UserId)
	}
	if in.Param.Username != "" {
		query = query.Where("user_name LIKE ?", "%"+in.Param.Username+"%")
	}
	if in.Param.Cpf != "" {
		query = query.Where("cpf = ?", in.Param.Cpf)
	}
	if in.Param.WalletType != 0 {
		query = query.Where("wallet_type = ?", in.Param.WalletType)
	}
	var total int64

	query = query.Count(&total).Limit(int(in.Page.PageSize)).Offset(int(offset))
	tx := query.Find(&userChannelPixInfos)

	var userPixWallets []*rpc.UserPixWalletsInfo

	if tx.Error != nil {
		return &rpc.UserPixWalletsPageResponse{
			DataList: userPixWallets,
			Total:    total,
		}, xerrors.ErrDataConvert
	}

	_ = copier.Copy(&userPixWallets, userChannelPixInfos)
	for i := 0; i < len(userPixWallets); i++ {
		userPixWallets[i].Id = userChannelPixInfos[i].Model.ID
	}
	return &rpc.UserPixWalletsPageResponse{
		DataList: userPixWallets,
		Total:    total,
	}, nil
}

func (m *PixWalletModel) UserPixWalletsUpdate(in *rpc.UserPixWalletsUpdateRequest) (*rpc.UserPixWalletsUpdatesResponse, error) {
	tx := m.db.Where("id = ?", in.Id).Updates(&channel.UserChannelPix{
		UserId:     in.UserId,
		UserName:   in.Username,
		Account:    in.Account,
		Cpf:        in.Cpf,
		WalletType: int32(in.WalletType),
	})
	if tx.Error != nil || tx.RowsAffected == 0 {
		return nil, xerrors.ErrUpdate
	}
	m2 := withdraw.NewUserAuthModel(m.ctx, m.db)
	m2.UserAuthModelUpdate(&rpc.UserAuth{
		ID:       in.Id,
		UserId:   in.UserId,
		UserName: in.Username,
		UserAuth: in.Cpf,
	})
	return &rpc.UserPixWalletsUpdatesResponse{
		IsUpdate: true,
	}, nil
}
